(function ($) {
	
    //全局系统对象
    window['jqueryUtil'] = {};

	jqueryUtil.autoUploadFile = function(file,onSuccess,onError){
		var formData = new FormData();
		formData.append("file",$(file).prop('files')[0]);
		$.ajax({
			type:'POST',
			url:"common/support/attachmentCommon!autoUploadFile.action",
			data:formData,
			contentType: false,// 注意：让jQuery不要处理数据
			processData: false,// 注意：让jQuery不要设置contentType
			success:function (msg) {
				onSuccess(msg);
			},
			error:function (msg) {
				onError(msg);
			}
		});
	};

	//IE检测
	jqueryUtil.isLessThanIe8 = function() {
		return ($.browser.msie && $.browser.version < 8);
	};
	
	jqueryUtil.procException = function(result) {
		if(result == null) return true;
		if(result.exception) {
			$.messager.alert('发生异常', result.exception);
			return true;
		}
		return false;
	};
	
	jqueryUtil.jsonPost = function(url,params,sucFunc) {
		$.post(url,params,function(rsp) {
			if(rsp != null && typeof rsp.exception == 'undefined') {		//没有异常
				sucFunc(rsp);
			}
		},'JSON');
	};
		
	//序列化表单到对象
	jqueryUtil.serializeObject = function(form) {
		//console.dir(form.serializeArray());
		var o = {};
		$.each(form.serializeArray(), function(index) {
			if (o[this['name']]) {
				o[this['name']] = o[this['name']] + "," + (this['value']==''?' ':this['value']);
			} else {
				o[this['name']] = this['value']==''?' ':this['value'];
			}
		});
		//console.dir(o);
		return o;
	};
		
	//cookies
	 jqueryUtil.cookies = (function ()
    {
        var fn = function ()
        {
        };
        fn.prototype.get = function (name)
        {
            var cookieValue = "";
            var search = name + "=";
            if (document.cookie.length > 0)
            {
                offset = document.cookie.indexOf(search);
                if (offset != -1)
                {
                    offset += search.length;
                    end = document.cookie.indexOf(";", offset);
                    if (end == -1) end = document.cookie.length;
                    cookieValue = decodeURIComponent(document.cookie.substring(offset, end))
                }
            }
            return cookieValue;
        };
        fn.prototype.set = function (cookieName, cookieValue, DayValue)
        {
            var expire = "";
            var day_value = 1;
            if (DayValue != null)
            {
                day_value = DayValue;
            }
            expire = new Date((new Date()).getTime() + day_value * 86400000);
            expire = "; expires=" + expire.toGMTString();
            document.cookie = cookieName + "=" + encodeURIComponent(cookieValue) + ";path=/" + expire;
        }
        fn.prototype.remvoe = function (cookieName)
        {
            var expire = "";
            expire = new Date((new Date()).getTime() - 1);
            expire = "; expires=" + expire.toGMTString();
            document.cookie = cookieName + "=" + escape("") + ";path=/" + expire;
            /*path=/*/
        };

        return new fn();
    })();
	//获取随机时间
	 jqueryUtil.getRandTime=function(){
		 	var nowDate=new Date();
		 	var str="";
			var hour=nowDate.getHours();//HH
			str+=((hour<10)?"0":"")+hour;
			var min=nowDate.getMinutes();//MM
			str+=((min<10)?"0":"")+min;
			var sec=nowDate.getSeconds(); //SS
			str+=((sec<10)?"0":"")+sec;
			return Number(str);
	 };
	//切换皮肤
	jqueryUtil.chgSkin=function(selectId,cookiesColor){
        	 docchgskin(document,selectId,cookiesColor);
            $("iframe").each(function (){   
                var dc=this.contentWindow.document;
                docchgskin(dc,selectId,cookiesColor);
            });
            function docchgskin(dc,selectId,cookiesColor){
						removejscssfile(dc,"resources/easyui/themes/"+cookiesColor+"/easyui.css", "css");
                        createLink(dc,"resources/easyui/themes/"+selectId+"/easyui.css");
        	}
            function createLink(dc,url){
		    	var urls = url.replace(/[,]\s*$/ig,"").split(",");
		    	var links = [];
		    	for( var i = 0; i < urls.length; i++ ){
			    links[i] = dc.createElement("link");
			    links[i].rel = "stylesheet";
			    links[i].href = urls[i];
			    dc.getElementsByTagName("head")[0].appendChild(links[i]);
		     	}
	    	}
            function removejscssfile(dc,filename, filetype){
	            var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none"
	            var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none"
	            var allsuspects=dc.getElementsByTagName(targetelement)
	            for (var i=allsuspects.length; i>=0; i--)
	            {
	                if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
	                allsuspects[i].parentNode.removeChild(allsuspects[i])
	            }
        	}  
        };
        
        /**
         * 在已有的URL上添加参数信息
         * @param {} url 原URL信息
         * @param {} name 添加参数的名称
         * @param {} value 添加参数的值
         * @return {} 添加参数后的新url
         */
        jqueryUtil.appendURL = function(url,name,value) {
        	if(url.indexOf("?") != -1) {
        		return url += "&"+name+"="+value;
        	} else {
        		return url += "?"+name+"="+value;
        	}
        };
		
		$.loadJSFiles = function(filenames,func) {
			if(filenames.length == 0) {
				func();
				return;
			}
			var file = filenames[0];
			$.loadJSFile(file.url,file.id,function loadCountFunc() {
				var newAry = new Array;
				for(var i=1;i<filenames.length;i++)	newAry[i-1] = 	filenames[i];
				$.loadJSFiles(newAry,func);	
			});
		};
		
		$.loadJSFile = function(filename, scriptID,func) {
			scriptID = MD5(filename);
			if(typeof loadMaskDiv != "undefined" && loadMaskDiv) {
				document.getElementById("_load_span").innerHTML = "<br><br><center>正在加载文件:"+scriptID+"...</center><p>" ;
			}
			if (filename && scriptID) {
				var oldscript = document.getElementById(scriptID);
				if (!oldscript) {
					var index = filename.indexOf('?');
					if (index >= 0) filename = filename + "&timeStamp="+new Date().getTime();
					else filename = filename + "?timeStamp="+new Date().getTime();
					var scriptContainer	= document.createElement('script');			//创建标签 
					scriptContainer.setAttribute("id", scriptID);
			  		scriptContainer.setAttribute("type","text/javascript");			//定义属性type的值为text/javascript 
			  		scriptContainer.setAttribute("src", filename);					//文件的地址 
			  		document.body.appendChild(scriptContainer);
		        	if(scriptContainer.attachEvent) { //IE
		       			scriptContainer.onreadystatechange=function(){
			　　　　	if(scriptContainer.readyState=='loaded' || scriptContainer.readyState=='complete'){
			　　　　　　func();
			　　　　	}
		　　　　	};
		        	} else {			//firefox
		        		scriptContainer.onload = function(){
			　　　　　func();
		　　　　	};
		        	}
				} else {
					var oldsrc = oldscript.getAttribute('src'), newsrc = filename;
					var pos = oldsrc.indexOf('/');
					if (pos >= 0) {
						oldsrc = oldsrc.substring(pos);
					}
					pos = newsrc.indexOf('/');
					if (pos >= 0) {
						newsrc = newsrc.substring(pos);
					}
					if (newsrc.indexOf(oldsrc) < 0 && oldsrc.indexOf(newsrc) < 0) {
						throw {message:'scriptID:' + scriptID + ' 转载的JS文件src:' + filename + '和原来的' + oldscript.getAttribute('src') + '不匹配'};
					}
					func(); 
				}
			} else {
				throw {message:'转载的JS文件ID:' + scriptID + " 或者文件名错误:" + filename};
			}
		};
		
		$.download = function (option) {
			var url = option.url;
			var params = option.params;
			var method = option.method;
			// 获取url和params
			if (url && params) {
			    // 把参数组装成 form的  input
			    var inputs = '';
			    $.each(params, function ( item , val) {
			    	inputs += '<input type="hidden" name="' + item + '" value="' + val + '" />';
			    });
			    // request发送请求
			    $('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>').appendTo('body').submit().remove();
			};
	    };
	    
	    /* 
		 * 格式化字符串
		 */
	    $.formatString = function(str) {
	    	for ( var i = 0; i < arguments.length - 1; i++) {
	    		str = str.replace("{" + i + "}", arguments[i + 1]);
	    	}
	    	return str;
	    };
	    
	    /*
	     *将数组转换为分隔字符串
	     */
	    $.arrayToStr = function(array,split) {
	    	var str = "";
	    	var _split = split ? split : ",";
	    	for(var i=0;i<array.length;i++) {
	    		if(i == 0) str = array[i];
	    		else str = str + _split + array[i];
	    	}
	    	return str;
	    };
		
		/**
		 * @requires jQuery,EasyUI
		 * 创建一个模式化的dialog
		 * @returns $.modalDialog.handler 这个handler代表弹出的dialog句柄
		 * @returns $.modalDialog.xxx 这个xxx是可以自己定义名称，主要用在弹窗关闭时，刷新某些对象的操作，可以将xxx这个对象预定义好
		 * 
		 * o(*￣▽￣*)o 注: 此方法修改目的是为了兼容以前已使用的 固定的按钮 [保存、取消]按钮的弹出框 by bjlong
		 */
		$.modalDialog = function(options) {
			if ($.modalDialog.handler == undefined) {// 避免重复弹出
				var opts = $.extend({
					title : '',
					width : 840,
					height : 680,
					modal : true,
					onClose : function() {
						$.modalDialog.handler = undefined;
						$(this).dialog('destroy');
					}
				}, options);
				opts.modal = true;// 强制此dialog为模式化，无视传递过来的modal参数
				var buttons = opts.buttons;
				delete opts["buttons"];
				$.modalDialog.handler = $('<div/>').dialog(opts);
				if(buttons && buttons.length > 0) {
					var divContent = $.modalDialog.handler.find(".panel");
					var divButtons = $("<div class=\"dialog-button\"></div>");
					divContent.after(divButtons);
					
					if(buttons && buttons.length > 0) {
						for(var i=0; i<buttons.length; i++) {
							var a = $('<a href="javascript:void(0)" class="button-rightpadding"></a>');
							if(buttons[i].id && $.trim(buttons[i].id) != "") a.attr("id", buttons[i].id);
							var spanContentText = (buttons[i].iconCls && $.trim(buttons[i].iconCls) != "") ? "<span class='" + buttons[i].iconCls + "'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>" : "";
							spanContentText = (spanContentText + buttons[i].text);
							var spanContent = $("<span class='button button-raised button-royal'>" + spanContentText + "</span>");
							spanContent.appendTo(a.appendTo(divButtons));
							if (buttons[i].handler) {
		                        a[0].onclick = buttons[i].handler;
		                    }
						}
					}
					divContent.height(divContent.height()-50);
				}
				return $.modalDialog.handler;
			}
		};
		
		
		/**
		 * @requires jQuery,EasyUI
		 * 创建一个附带自定义按钮的模式化的dialog (按钮将固定显示在dialog底部位置)
		 * 按钮的属性 必须包含 
		 * 1, 显示名称:text
		 * 2, 按钮标识:id 或者 按钮点击处理事件: handler (因为实际情况 可能在js中动态添加需要使用id找到按钮. 也可能在初始化dialog时已定义点击处理事件handler)
		 * 
		 * 可选属性
		 * 1, 按钮背景颜色: bgColor (十六进制 颜色值)
		 * 2, 按钮文字颜色: txtColor (十六进制 颜色值)
		 * 3, 按钮显示图标: iconCls	(easyui 图标 class名称)
		 */
		$.customBtnsModalDialog = function(options) {
			var opts = $.extend({title : '',width : 840,height : 680,modal : true,onClose : function() {$(this).dialog('destroy');}}, options);
			opts.modal = true; // 强制此dialog为模式化，无视传递过来的modal参数
			var buttons = opts.buttons;
			delete opts["buttons"];
			var divDialog = $('<div/>').dialog(opts);
			if(buttons && buttons.length > 0) {
				var divContent = divDialog.find(".panel");
				var divButtons = $("<div class=\"dialog-button\"></div>");
				divContent.after(divButtons);
				if(buttons && buttons.length > 0) {
					for(var i=0; i<buttons.length; i++) {
						var a = $('<a href="javascript:void(0)" class="button-rightpadding"></a>');
						if(buttons[i].id && $.trim(buttons[i].id) != "") a.attr("id", buttons[i].id);
						var spanContentText = (buttons[i].iconCls && $.trim(buttons[i].iconCls) != "") ? "<span class='" + buttons[i].iconCls + "'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>" : "";
						spanContentText = (spanContentText + buttons[i].text);
						var spanContent = $("<span class='button button-raised button-royal'>" + spanContentText + "</span>");
						if(buttons[i].bgColor)	spanContent.css("background", buttons[i].bgColor); // 是否在参数中 传递了按钮的背景颜色
						if(buttons[i].txtColor) spanContent.css("color", buttons[i].txtColor); // 是否在参数中 传递了按钮的文字颜色
						spanContent.appendTo(a.appendTo(divButtons));
						if (buttons[i].handler) {
	                        a[0].onclick = buttons[i].handler;
	                    }
					}
				}
				divContent.height(divContent.height()-50);
			}
			return divDialog;
		};

		$.showMessage = function(message,title,pauseSecond) {
			$.messager.show({
				title : title ? title : "提示",
				msg : message,
				timeout : pauseSecond ? pauseSecond : 1000 * 3
			});
		}
})(jQuery);